package com.ics.cmsadmin.modules.api.controller;

import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.bean.PageResult;
import com.ics.cmsadmin.frame.core.enums.ApiResultEnum;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.basic.bean.OrderBean;
import com.ics.cmsadmin.modules.basic.service.StudentOrderService;
import com.ics.cmsadmin.modules.pub.bean.OrderForm;
import com.ics.cmsadmin.modules.sso.utils.SsoUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Api(description = "买家订单api")
@RestController
@RequestMapping("/api/buyer/order")
@Log4j2
public class ApiStudentOrderController {

    @Autowired
    private StudentOrderService studentOrderService;

    @ApiOperation("创建订单")
    @PostMapping("/create")
    public ApiResponse create(@Valid OrderForm orderForm,
                              BindingResult bindingResult,
                              HttpServletRequest request) {
        String loginUserId = SsoUtils.getLoginUserId(request);

        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm = {}", orderForm);
            throw new CmsException(ApiResultEnum.PARAM_ERROR);
        }

        OrderBean order = studentOrderService.create(orderForm, loginUserId);
        return ApiResponse.getDefaultResponse(order);
    }

    @ApiOperation("买家端查询订单列表")
    @GetMapping("/list")
    public ApiResponse list(HttpServletRequest request,
                            @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        String userId = SsoUtils.getLoginUserId(request);

        PageBean page = new PageBean(pageNo, pageSize);
        PageResult pageResult = studentOrderService.list(userId, page);
        return ApiResponse.getDefaultResponse(pageResult);
    }
}
